package controller.Actions;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Erro;
import model.SearchAccount;
import model.User;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONArray;
import org.json.JSONObject;

import dao.SearchAccountDAO;


public class SearchAccountAction extends Action {
	
	  @Override
	public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {

            User u = (User) request.getSession().getAttribute("User");
            if (u == null) {
                request.getSession().setAttribute("ErroMSG", Erro.erroMsg[Erro.NAO_AUTENTICADO]);
                return mapping.findForward("erroAlias");
            } else {

                SearchAccountDAO gpDAO = new SearchAccountDAO();

                String key = request.getParameter("key");
                ArrayList<SearchAccount> listaContas = gpDAO.readByKey(key);

                JSONArray array = new JSONArray();

                for (SearchAccount listaConta : listaContas) {
                    JSONObject object = new JSONObject();

                    object.put("id", listaConta.getId());
                    object.put("descricao", listaConta.getDescricao());
                    object.put("extendida", listaConta.getDescextendida());

                    array.put(object);
                }

                String jsonResult = array.toString();
                response.setContentType("text/javascript; charset=utf-8");
                response.getWriter().write(jsonResult);
                gpDAO.closeDAO();

                
                

                return null;
            }

        } catch (Exception e) {
        	System.out.println(e.getMessage());
            return mapping.findForward("erroAlias");
        }
    }


}
